package com.adam.springbucks.untils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
//import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class HttpRequestUtils {
    private static Logger logger = LoggerFactory.getLogger(HttpRequestUtils.class); // 日志记录


    /**
     * post请求
     *
     * @param url url地址
     * @return
     */
    public static String httpPost(String url, String reqBody) {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        String jsonResult = null;
        System.out.println("url：" + url);
        System.out.println("requestBody：" + reqBody);
        HttpPost method = new HttpPost(url);
        try {
            if (reqBody!=null && !"".equals(reqBody)) {
                StringEntity entity = new StringEntity(reqBody, "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/text");
                method.setEntity(entity);
            }
            HttpResponse result = httpClient.execute(method);
            if (result.getStatusLine().getStatusCode() == 200) {
                String str = "";
                try {
                    str = EntityUtils.toString(result.getEntity());
                    jsonResult = str;
                } catch (Exception e) {
                    logger.error("post请求提交失败:" + url, e);
                }
            }
        } catch (IOException e) {
            logger.error("post请求提交失败:" + url, e);
        }
        System.out.println("response:" + jsonResult);
        return jsonResult;
    }

    /**
     * 发送get请求
     *
     * @param url 路径
     * @return
     */
    public static String httpGet(String url) {
        String jsonResult = null;
        try {
            DefaultHttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet(url);
            HttpResponse response = client.execute(request);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String strResult = EntityUtils.toString(response.getEntity());
                jsonResult = strResult;
            } else {
                logger.error("get请求提交失败:" + url);
            }
        } catch (IOException e) {
            logger.error("get请求提交失败:" + url, e);
        }
        return jsonResult;
    }

    /**
     * 发送get请求 验证权限
     *
     * @param url 路径
     * @return
     */
    public static String httpGetAndCookie(String url, String sessionId) {
        String jsonResult = null;
        try {
            DefaultHttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet(url);
            request.setHeader(new BasicHeader("Cookie", "JSESSIONID=" + sessionId));
            HttpResponse response = client.execute(request);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String strResult = EntityUtils.toString(response.getEntity());
                jsonResult = strResult;
            } else {
                logger.error("get请求提交失败:" + url);
            }
        } catch (IOException e) {
            logger.error("get请求提交失败:" + url, e);
        }
        return jsonResult;
    }



   static public String doGet(String url) throws URISyntaxException, IOException, HttpException {

      return doGet(url, null, null);
   }

   static public String doGet(String url, JSONObject params) throws URISyntaxException, IOException, HttpException {
      return doGet(url, null, params);
   }

   static public String doGet(String url, String token, JSONObject params)
         throws URISyntaxException, IOException, HttpException {
      HttpClientBuilder builder = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy());

      CloseableHttpClient httpClient = builder.build();

      List<NameValuePair> nvps = toNvps(params);

      HttpGet get = new HttpGet(new URIBuilder(url).addParameters(nvps).build());

      if (token != null) {
         get.setHeader(new BasicHeader("Cookie", "_tid=" + token + ";JSESSIONID=" + token));
         // get.setHeader(new BasicHeader("JSESSIONID", token));
      }

      HttpResponse response = httpClient.execute(get);

      int code = response.getStatusLine().getStatusCode();

      String resultText = EntityUtils.toString(response.getEntity());

      logger.info("url={},nvps={},response={}", url, nvps, resultText);

      if (code != HttpStatus.SC_OK) {
         String message = String.format(" url=%s, parameters=%s, HttpCode=%s, responseText=%s", url, nvps, code,
               resultText);
         httpClient.close();
         throw new HttpException(message);
      }

      httpClient.close();

      return resultText;
   }

   static public String doPost(String url, String data) throws URISyntaxException, IOException, HttpException {
      return doPost(url, null, data);
   }

   static public String doPost(String url, String token, String data)
         throws URISyntaxException, IOException, HttpException {
      HttpClientBuilder builder = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy());

      CloseableHttpClient httpClient = builder.build();

      HttpPost post = new HttpPost(url);

      post.setHeader(new BasicHeader("Cookie", "_tid=" + token + ";JSESSIONID=" + token));

      post.setEntity(new StringEntity(data, ContentType.APPLICATION_JSON));

      HttpResponse response = httpClient.execute(post);

      int code = response.getStatusLine().getStatusCode();

      String resultText = EntityUtils.toString(response.getEntity());

      if (code != HttpStatus.SC_OK) {
         httpClient.close();
         throw new HttpException(resultText);
      }

      httpClient.close();

      return resultText;
   }

   static public String doPost(String url, Map<String, String> params)
         throws URISyntaxException, IOException, HttpException {

      List<NameValuePair> nvps = new ArrayList<>();
      for (String key : params.keySet()) {
         nvps.add(new BasicNameValuePair(key, params.get(key)));
      }

      return doPost(url, nvps);
   }

   static public String doPost(String url, List<NameValuePair> nvps)
         throws URISyntaxException, IOException, HttpException {
      HttpClientBuilder builder = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy());

      CloseableHttpClient httpClient = builder.build();

      HttpPost post = new HttpPost(url);

      post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

      logger.info("url={},nvps={}", url, nvps);

      HttpResponse response = httpClient.execute(post);

      int code = response.getStatusLine().getStatusCode();

      String resultText = EntityUtils.toString(response.getEntity());

      logger.info("url={},nvps={},response={}", url, nvps, resultText);

      if (code != HttpStatus.SC_OK) {
         httpClient.close();
         throw new HttpException(resultText);
      }

      httpClient.close();

      return resultText;
   }

   private static List<NameValuePair> toNvps(JSONObject jsonObject) {
      List<NameValuePair> nvps = new ArrayList<>();
      if (jsonObject != null) {
         Set<String> keys = jsonObject.keySet();
         for (String key : keys) {
            nvps.add(new BasicNameValuePair(key, jsonObject.getString(key)));
         }
      }
      return nvps;
   }

//   static public String upload(String url, byte[] bytes) throws IOException, HttpException {
//      HttpClientBuilder builder = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy());
//
//      CloseableHttpClient httpClient = builder.build();
//
//      HttpPost post = new HttpPost(url);
//
//      MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
//      multipartEntityBuilder.addBinaryBody("file", bytes, ContentType.MULTIPART_FORM_DATA, "file");
//      post.setEntity(multipartEntityBuilder.build());
//      // post.setHeader("Content-Type","multipart/form-data;charset=utf-8");
//
//      HttpResponse response = httpClient.execute(post);
//
//      int code = response.getStatusLine().getStatusCode();
//
//      if (code != org.apache.http.HttpStatus.SC_OK) {
//         httpClient.close();
//         throw new HttpException();
//      }
//
//      String resultText = EntityUtils.toString(response.getEntity());
//      httpClient.close();
//
//      return resultText;
//   }
//
//   static public String upload(String url, File file) throws IOException, HttpException {
//      HttpClientBuilder builder = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy());
//
//      CloseableHttpClient httpClient = builder.build();
//
//      HttpPost post = new HttpPost(url);
//
//      MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
//      multipartEntityBuilder.addBinaryBody("file", file);
//      post.setEntity(multipartEntityBuilder.build());
//      // post.setHeader("Content-Type","multipart/form-data;charset=utf-8");
//
//      HttpResponse response = httpClient.execute(post);
//
//      int code = response.getStatusLine().getStatusCode();
//
//      if (code != org.apache.http.HttpStatus.SC_OK) {
//         httpClient.close();
//         throw new HttpException();
//      }
//
//      String resultText = EntityUtils.toString(response.getEntity());
//      httpClient.close();
//
//      return resultText;
//   }
}